// 云函数入口文件
const cloud = require('wx-server-sdk')
// 引入TcbRouter
const TcbRouter = require('tcb-router')
// 引入axios
const axios = require('axios')
// 获取歌单详情地址
// const BASE_URL = 'http://musicapi.xiecheng.live'
const BASE_URL = 'https://apis.imooc.com'
const ICODE = 'icode=8A57B2DAC6712EA6'

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  // 获得tcbRouter实例
  const app = new TcbRouter({
    event
  })
  // 获取歌单列表
  app.router('playlist', async(ctx, next) => {
    ctx.body = await cloud.database().collection('playlist')
    .skip(event.start)
    .limit(event.count)
    .orderBy('createTime', 'desc')
    .get()
  })
  // 根据歌单id,获取歌单详情
  app.router('musiclist', async(ctx, next) => {
    const { data } = await axios.get(`${BASE_URL}/playlist/detail?id=${parseInt(event.playlistId)}&${ICODE}`)
    ctx.body = data
  })
  // 根据歌曲id获取歌曲信息
  app.router('musicUrl', async(ctx, next) => {
    const { data } = await axios.get(`${BASE_URL}/song/url?id=${event.musicId}&${ICODE}`)
    ctx.body = data
  })

  // 获取歌词
  app.router('lyric', async(ctx, next) => {
    const { data } = await axios.get(`${BASE_URL}/lyric?id=${event.musicId}&${ICODE}`)
    ctx.body = data
  })

  return app.serve()
}